package com.demo.config;

import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@PropertySource({"classpath:db.properties"})
@ComponentScan("com.demo")
@MapperScan("com.demo.mapper")
public class MyBatisConfig {
    @Value("${database.driverClassName}")
    private String driverClassName;
    @Value("${database.url}")
    private String url;
    @Value("${database.username}")
    private String username;
    @Value("${database.password}")
    private String password;
    @Value("${MapperLocations}")
    private String mapperLocations;

    @Value("${MapperConfiguration}")
    private String mapperConfiguration;
    @Value("${TypeAliasesPackage}")
    private String typeAliasesPackage;

    @Bean
    public DataSource dataSource(){
        // 使用Hikari数据库连接池
        HikariDataSource hikariDataSource = new HikariDataSource();
        // 设置数据库驱动
        hikariDataSource.setDriverClassName(driverClassName);
        // 设置数据库的url
        hikariDataSource.setJdbcUrl(url);
        // 设置数据库账号
        hikariDataSource.setUsername(username);
        // 设置数据库密码
        hikariDataSource.setPassword(password);
        // 返回设置好的数据源对象
        return hikariDataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        // 创建整合spring的SqlSessionFactoryBean对象，方便调用afterPropertiesSet
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置数据库的相关参数，用户名，密码，url，驱动等信息
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 定义spring的xml解析
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 设置定义mapper查询语句的路径地址
        Resource[] mapperXML = resolver.getResources(mapperLocations);
        // 设置定义mybatis-config.xml
        Resource mapperConfResource = resolver.getResource(mapperConfiguration);
        // 设置mapper的映射路径
        sqlSessionFactoryBean.setMapperLocations(mapperXML);
        // 设置Configuration的全局配置文件，如果不设置的话，那么它会在static代码块中默认加载和创建一个对象。
        sqlSessionFactoryBean.setConfigLocation(mapperConfResource);
        // 设置实体类名的包
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        return sqlSessionFactoryBean;
    }
}
